package com.bycx.core.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.remoting.caucho.HessianServiceExporter;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import com.alibaba.fastjson.JSONObject;
import com.bycx.core.annotation.WechatNeedLogin;
import com.bycx.core.startup.AppConfig;
import com.bycx.core.util.Page;
import com.bycx.wechat.util.WeChatSessionUtil;

public class WechatSecurityInterceptor extends HandlerInterceptorAdapter {
	private Log log = LogFactory.getLog(WechatSecurityInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest req,
			HttpServletResponse res,
			Object handler) throws Exception {

		String contextPath = req.getContextPath();
		req.setAttribute("contextPath", contextPath);

		// 拦截非微信端访问
		Boolean wxForceEnable = AppConfig.getBoolean("wx_force_enable");
		wxForceEnable = wxForceEnable == null ? true : wxForceEnable;
		if (wxForceEnable) {
			String uri = req.getRequestURI();
			String userAgent = req.getHeader("user-agent");
			if (uri.matches("/wechat/.+") && userAgent.indexOf("MicroMessenger") < 0) {
				res.setContentType("text/html;charset=UTF-8");
				PrintWriter pw = null;
				try {
					pw = res.getWriter();
					pw.println("<script>");
					pw.println("alert('该页面仅支持微信内部访问！');");
					pw.println("window.close();");
					pw.println("</script>");
				} finally {
					if (pw != null)
						pw.close();
				}

				log.warn("强制微信访问过滤，uri=" + uri + "；userAgent=" + userAgent);
				return false;
			}
		}

		if (handler == null)
			return true;
		else if (handler instanceof DefaultServletHttpRequestHandler)
			return true;
		// 静态资源放行
		else if (handler instanceof ResourceHttpRequestHandler)
			return true;
		// Hessian接口请求放行
		else if (handler instanceof HessianServiceExporter)
			return true;
		// 如果是正常的Spring MVC请求
		else if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;

			// 登录拦截：如果要求登录却没有登录
			if (handlerMethod.hasMethodAnnotation(WechatNeedLogin.class)) {
				if (!WeChatSessionUtil.checkLogin()) {
					if (handlerMethod.hasMethodAnnotation(ResponseBody.class)) {
						Page<Object> page = new Page<>();
						page.setSuccess(false);
						page.setMsg("请先登录！");
						page.setCode("-1");
						res.setContentType("application/json;charset=UTF-8");
						res.getWriter().write(JSONObject.toJSONString(page));
					} else {
						res.sendRedirect(contextPath + "/wechat/login");
					}
					return false;
				}
			}

			return true;
		} else
			return false;
	}

	@Override
	public void postHandle(HttpServletRequest req,
			HttpServletResponse res,
			Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(req, res, handler, modelAndView);
	}

	@Override
	public void afterCompletion(HttpServletRequest req,
			HttpServletResponse res,
			Object handler,
			Exception e) throws Exception {
		super.afterCompletion(req, res, handler, e);
	}

	@Override
	public void afterConcurrentHandlingStarted(HttpServletRequest req,
			HttpServletResponse res,
			Object handler) throws Exception {
		super.afterConcurrentHandlingStarted(req, res, handler);
	}

}
